$(function() {
	var month = '';
	var userInfo = ''; //用户登录返回信息
	var billInfo = ''; //账单详情
	var shangguanArr = []; //商管数组
	var wuguanArr = []; //物管数组
	var otherArr = []; //其他数组
	var sgAccidArr = []; //商管id数组
	var wgAccidArr = []; //物业id数组
	var otherAccidArr = []; //其他id数组
	var accidArr = []; //accid数组
	var contentType = 0; //缴费时判断所属类型是商管还是物管，0为商管，1为物业
	var sgAccount = ''; //商管银行账号
	var wyAccount = ''; //物业银行账号
	var billNumber;

	function init() {
		if(handleUrl().month) {
			month = handleUrl().month.substring(0, 4) + handleUrl().month.substring(5, 7);
		}

		userInfo = JSON.parse(decodeURI(decodeURI(sessionStorage.getItem('jf_user_info'))));
		console.log(userInfo)
		if(userInfo) {
			var postData = {
				contract: userInfo.stores[0].contracts[0].uuid,
				beginSettle: month,
				endSettle: month
			}

			function successFun(res) {
				billInfo = res;
				if(billInfo) {
					$('.accountName').html(userInfo.name); //填充商户账号
					$('.billTime').html(handleUrl().month);
					$('#payTotal').html(billInfo.data.payTotal);
					$('#payedTotal').html(billInfo.data.payedTotal);
					$('#unpayedTotal').html(billInfo.data.unpayedTotal);
					$('#payRate').html(((billInfo.data.payedTotal / billInfo.data.payTotal) * 100).toFixed(2) + '%');

					handleBillDetail(billInfo, userInfo);
				}
			}
			_http.queryBill(postData, successFun);

		} else {
			window.location.href = "../index.html";
		}
	}
	init();

	function handleBillDetail(billInfo, userInfo) {

		for(var j = 0; j < userInfo.companies.length; j++) {
			for(var k = 0; k < userInfo.companies[j].subjects.length; k++) {

				for(var i = 0; i < billInfo.data.subjects.length; i++) {
					var isOther = true;
					var status = handleStatus(billInfo.data.subjects[i].confirmed, billInfo.data.subjects[i].unpayedTotal).status;
					var hideInput = handleStatus(billInfo.data.subjects[i].confirmed, billInfo.data.subjects[i].unpayedTotal).hideInput;
					var billname = billInfo.data.subjects[i].subject.name;
					var beginDate = billInfo.data.subjects[i].beginDate;
					var endDate = billInfo.data.subjects[i].endDate.split(' ')[0];
					var payTotal = billInfo.data.subjects[i].payTotal;
					var payedTotal = billInfo.data.subjects[i].payedTotal;
					var unpayedTotal = billInfo.data.subjects[i].unpayedTotal;
					var billType = '';
					var fontColor = '#E5001C';
					var disabled = 'disabled';
					if(status == '未确认') {
						fontColor = '#E5001C'; //红色
						disabled = '';
					} else if(status == '已确认') {
						fontColor = '#3385ff'; //蓝色
						disabled = 'disabled';
					} else if(status == '已缴款') {
						fontColor = '#337002';
					}

					if(billInfo.data.subjects[i].subject.uuid == userInfo.companies[j].subjects[k].uuid) {
						isOther = false;
						billType = userInfo.companies[j].name;
						if(userInfo.companies[j].companyType == "商管公司") {
							sgAccount = userInfo.companies[j].account; //将商管银行账户赋值

							shangguanArr.push(billInfo.data.subjects[i]); //加入商管数组中
							$('.shangguan').show();
							$('.shangguan thead th>span').html(billType);
							$('.shangguan tbody').append('<tr>' +
								'<td class="text-center"><input class="' + hideInput + '" type="checkbox" name="shangguan" ' + disabled + ' /></td>' +
								'<td>' +
								'<div class="detailItem fl">' +
								'<p class="fc-black">' + billname + '</p>' +
								'<p>' + beginDate + '~' + endDate + '</p>' +
								'</div>' +
								'<div class="itemPayInfo f16 fl">' +
								'<label>应缴：<span>' + payTotal + '</span>元</label>&nbsp;&nbsp;&nbsp;&nbsp;' +
								'<label class="fc-darkgreen">已缴：<span>' + payedTotal + '</span>元</label>&nbsp;&nbsp;&nbsp;&nbsp;' +
								'<label class="fc-red">未缴：<span>' + unpayedTotal + '</span>元</label>' +
								'</div>' +
								'<span class="fr billStatus" style="color:' + fontColor + '">' + status + '</span>' +
								'</td>' +
								'</tr>')
						} else if(userInfo.companies[j].companyType == "物业公司" || userInfo.companies[j].companyType == "物管公司") {
							wyAccount = userInfo.companies[j].account; //将物业银行账户赋值
							wuguanArr.push(billInfo.data.subjects[i]); //加入物管数组中
							$('.wuguan').show();
							$('.wuguan thead th>span').html(billType);
							$('.wuguan tbody').append('<tr>' +
								'<td class="text-center"><input class="' + hideInput + '" type="checkbox" name="shangguan" ' + disabled + ' /></td>' +
								'<td>' +
								'<div class="detailItem fl">' +
								'<p class="fc-black">' + billname + '</p>' +
								'<p>' + beginDate + '~' + endDate + '</p>' +
								'</div>' +
								'<div class="itemPayInfo f16 fl">' +
								'<label>应缴：<span>' + payTotal + '</span>元</label>&nbsp;&nbsp;&nbsp;&nbsp;' +
								'<label class="fc-darkgreen">已缴：<span>' + payedTotal + '</span>元</label>&nbsp;&nbsp;&nbsp;&nbsp;' +
								'<label class="fc-red">未缴：<span>' + unpayedTotal + '</span>元</label>' +
								'</div>' +
								'<span class="fr billStatus" style="color:' + fontColor + '">' + status + '</span>' +
								'</td>' +
								'</tr>')
						}
					}
				}
			}
		}
		for(var i = 0; i < billInfo.data.subjects.length; i++) {
			var isOther = true;
			var status = handleStatus(billInfo.data.subjects[i].confirmed, billInfo.data.subjects[i].unpayedTotal).status;
			var hideInput = handleStatus(billInfo.data.subjects[i].confirmed, billInfo.data.subjects[i].unpayedTotal).hideInput;
			var billname = billInfo.data.subjects[i].subject.name;
			var beginDate = billInfo.data.subjects[i].beginDate;
			var endDate = billInfo.data.subjects[i].endDate.split(' ')[0];
			var payTotal = billInfo.data.subjects[i].payTotal;
			var payedTotal = billInfo.data.subjects[i].payedTotal;
			var unpayedTotal = billInfo.data.subjects[i].unpayedTotal;
			var billType = '';
			var fontColor = '#E5001C';
			var disabled = 'disabled';
			if(status == '未确认') {
				fontColor = '#E5001C'; //红色
				disabled = '';
			} else if(status == '已确认') {
				fontColor = '#3385ff'; //蓝色
				disabled = 'disabled';
			} else if(status == '已缴款') {
				fontColor = '#337002';
			}

			for(var j = 0; j < userInfo.companies.length; j++) {
				for(var k = 0; k < userInfo.companies[j].subjects.length; k++) {
					if(billInfo.data.subjects[i].subject.uuid == userInfo.companies[j].subjects[k].uuid) {
						isOther = false;
					}
				}
			}
			if(isOther) {
				billType = '其他';
				otherArr.push(billInfo.data.subjects[i]); //加入其他数组中
				$('.other').show();
				$('.other thead th>span').html(billType);
				$('.other tbody').append('<tr>' +
					'<td class="text-center"><input class="' + hideInput + '" type="checkbox" name="shangguan" ' + disabled + ' /></td>' +
					'<td>' +
					'<div class="detailItem fl">' +
					'<p class="fc-black">' + billname + '</p>' +
					'<p>' + beginDate + '~' + endDate + '</p>' +
					'</div>' +
					'<div class="itemPayInfo f16 fl">' +
					'<label>应缴：<span>' + payTotal + '</span>元</label>&nbsp;&nbsp;&nbsp;&nbsp;' +
					'<label class="fc-darkgreen">已缴：<span>' + payedTotal + '</span>元</label>&nbsp;&nbsp;&nbsp;&nbsp;' +
					'<label class="fc-red">未缴：<span>' + unpayedTotal + '</span>元</label>' +
					'</div>' +
					'<span class="fr billStatus" style="color:' + fontColor + '">' + status + '</span>' +
					'</td>' +
					'</tr>')
			}
		}
	}

	function handleStatus(confirmed, unpayedTotal) {
		var status = '';
		var hideInput = '';
		if(unpayedTotal <= 0 || unpayedTotal <= 0.00) {
			status = "已缴款";
			hideInput = 'hideInput';
		} else {
			hideInput = '';
			if(confirmed) {
				status = "已确认";
			} else {
				status = "未确认";
			}
		}

		return {
			status: status,
			hideInput: hideInput
		}
	}

	/**
	 * 仅显示欠缴
	 * */
	$('#screenBill').change(function() {
		var checked = $(this).prop('checked');
		if(checked) {
			$('table tbody tr').each(function() {
				var reg = new RegExp(('hideInput'));
				if($(this).find('input').attr('class')) {
					$(this).hide();
				}
			})
		} else {
			$('table tbody tr').each(function() {
				var reg = new RegExp(('hideInput'));
				if($(this).find('input').attr('class')) {
					$(this).show();
				}
			})
		}
	})

	/**
	 * checkbox选择框单选操作，确认和付款
	 * */
	$('table tbody tr input').change(function() {
		var index = $(this).parent().parent().index();
		var tableIndex = $(this).parent().parent().parent().parent().index(); //table的索引
		var checked = $(this).prop('checked');
		if(checked) {
			//0代表商管，1代表物管，2代表其他
			if(tableIndex == 0) {
				sgAccidArr.push(shangguanArr[index].accId); //将accid 加入数组
			} else if(tableIndex == 1) {
				wgAccidArr.push(wuguanArr[index].accId); //将accid 加入数组
			} else if(tableIndex == 2) {
				otherAccidArr.push(otherArr[index].accId); //将accid 加入数组
			}
			if($(this).parent().next().find('span.billStatus').html() == "未确认") {
				$(this).parent().parent().parent().prev().find('button.payBtn').html('确认').show();
			} else if($(this).parent().next().find('span.billStatus').html() == "已确认") {
				$(this).parent().parent().parent().prev().find('button.payBtn').html('缴费').show();
			}
			var calcNum = (parseFloat($(this).parent().parent().parent().prev().find('span.calcPrice').html()) + parseFloat($(this).parent().next().find('.itemPayInfo label:last-child span').html())).toFixed(2);
			$(this).parent().parent().parent().prev().find('span.calcPrice').html(calcNum);

			var hasChecedAll = true;
			//判断是否全部选择了
			$(this).parent().parent().parent().find('tr').each(function() {
				var reg = new RegExp('hideInput');
				if(!reg.test($(this).find('input').attr('class'))) {
					if(!$(this).find('input').prop('checked')) {
						hasChecedAll = false;
					}
				}
			})
			if(hasChecedAll) {
				$(this).parent().parent().parent().prev().find('input').prop('checked', true);
			}
		} else {
			var calcNum = (parseFloat($(this).parent().parent().parent().prev().find('span.calcPrice').html()) - parseFloat($(this).parent().next().find('.itemPayInfo label:last-child span').html())).toFixed(2);
			$(this).parent().parent().parent().prev().find('span.calcPrice').html(calcNum);
			var isAllUnchecked = true;
			//判断当前公司块内是否所有的checkbox都已经取消选择，如果没有，标记置为false
			$(this).parent().parent().siblings().each(function() {
				if($(this).find('input').prop('checked')) {
					isAllUnchecked = false;
				}
			})
			//如果没有选中项，将按钮隐藏
			if(isAllUnchecked) {
				$(this).parent().parent().parent().prev().find('button.payBtn').hide();
			}
			//取消全选
			$(this).parent().parent().parent().prev().find('input').prop('checked', false);

			//从accidArr中去掉某一项  0代表商管，1代表物管，2代表其他
			if(tableIndex == 0) {
				for(var i = 0; i < accidArr.length; i++) {
					if(accidArr[i] == shangguanArr[index].accId) {
						accidArr.splice(i, 1);
					}
				}
			} else if(tableIndex == 1) {
				for(var i = 0; i < accidArr.length; i++) {
					if(accidArr[i] == wuguanArr[index].accId) {
						accidArr.splice(i, 1);
					}
				}
			} else if(tableIndex == 2) {
				for(var i = 0; i < accidArr.length; i++) {
					if(accidArr[i] == otherArr[index].accId) {
						accidArr.splice(i, 1);
					}
				}
			}
		}
	})

	/**
	 * 全选操作
	 * */
	$('.checkAll').change(function() {
		var tableIndex = $(this).parent().parent().parent().parent().index();
		var checked = $(this).prop('checked');
		var self = this;
		accidArr = []; //清空内容
		//先清空对应数组的内容
		if(tableIndex == 0) {
			sgAccidArr = [];
		} else if(tableIndex == 1) {
			wgAccidArr = [];
		} else if(tableIndex == 2) {
			otherAccidArr = [];
		}
		if(checked) {
			var isAllUnconfirm = true;
			var length = 0;
			$(this).parent().parent().parent().next().find('tr').each(function() {
				var reg = new RegExp('hideInput');
				if(!reg.test($(this).find('input').attr('class'))) {
					$(this).find('input').prop('checked', true);
					var calcNum = (parseFloat($(self).parent().next().find('.calcPrice').html()) + parseFloat($(this).find('.itemPayInfo label:last-child span').html())).toFixed(2);
					$(self).parent().next().find('.calcPrice').html(calcNum);
					if($(this).find('span.billStatus').html() == '已确认') {
						isAllUnconfirm = false;
					}
					var index = $(this).index();
					//0代表商管，1代表物管，2代表其他
					if(tableIndex == 0) {
						sgAccidArr.push(shangguanArr[index].accId); //将accid 加入数组
					} else if(tableIndex == 1) {
						wgAccidArr.push(wuguanArr[index].accId); //将accid 加入数组
					} else if(tableIndex == 2) {
						otherAccidArr.push(otherArr[index].accId); //将accid 加入数组
					}
				} else {
					length++;
				}
			})
			if(isAllUnconfirm) {
				$(this).parent().next().find('button.payBtn').html('确认').show();
			} else {
				$(this).parent().next().find('button.payBtn').html('缴费').show();
			}
			if(length == $(this).parent().parent().parent().next().find('tr').length) {
				$(this).parent().next().find('button.payBtn').hide();
			}
		} else {
			$(this).parent().parent().parent().next().find('tr').each(function() {
				var reg = new RegExp('hideInput');
				if(!reg.test($(this).find('input').attr('class'))) {
					$(this).find('input').prop('checked', false);
				}
			})
			$(self).parent().next().find('.calcPrice').html('0.00');
			$(self).parent().next().find('button.payBtn').hide();
		}
	})

	/**
	 * 确认账单，支付账单操作
	 * */
	var lines = []; //需要传递的账单数组项
	var tempPayPrice = 0;
	var tempLines = new Array();
	$('.payBtn').click(function() {
		var tableIndex = $(this).parent().parent().parent().parent().parent().index();
		var allSubjects; //保存当前选中的table中的subjecs
		lines = []; //将lines置为空数组
		//0代表商管，1代表物管，2代表其他，将对应的id数组重新赋值
		if(tableIndex == 0) {
			accidArr = sgAccidArr;
			allSubjects = shangguanArr;
			contentType = 0;
		} else if(tableIndex == 1) {
			accidArr = wgAccidArr;
			allSubjects = wuguanArr;
			contentType = 1;
		} else if(tableIndex == 2) {
			accidArr = otherAccidArr;
			allSubjects = otherArr;
			contentType = 2;
		}
		var txt = $(this).html();
		//确认订单操作
		if(txt == "确认") {
			var isOk = true;
			$(this).parent().parent().parent().parent().next().find('tr').each(function() {
				if($(this).find('input').prop('checked') == true) {
					if($(this).find('span.billStatus').html() == '已确认') {
						isOk = false;
						layer.msg('请检查选择项，不能包含已确认选项');
						return false;
					}
				}
			})
			if(isOk) {
				function successFun(res) {
					window.location.reload();
				}
				_http.confirmBill(accidArr, successFun);
			}
		} else if(txt == "缴费") { //付款操作
			if(contentType != 0 && contentType != 1) { //既不是商管也不是物业，是其他的账单情况的时候，不能缴费
				layer.msg('该账单不能缴费');
				return;
			} else {
				var bankCode = ''; //银行账户
				var poundage = 6; //手续费

				if(contentType == 0) {
					bankCode = sgAccount;
				} else if(contentType == 1) {
					bankCode = wyAccount;
				}
				var isOk = true;
				$('.confirmMain').empty();
				lines = []; //将lines置为空数组
				$(this).parent().parent().parent().parent().next().find('tr').each(function() {
					var index = $(this).index();
					if($(this).find('input').prop('checked') == true) {
						if($(this).find('span.billStatus').html() == '未确认') {
							isOk = false;
							layer.msg('缴费不能包含未确认选项');
							return false;
						} else {
							$('.confirmMain').append('<p><span class="fl">' + $(this).find('.detailItem p:first-child').html() + $(this).find('.detailItem p:last-child').html() +'：</span><span class="fr fc-black">' + $(this).find('.itemPayInfo label:last-child span').html() + '元</span></p>')
							//如果lines数组长度为0，将手续费置为6，否则置为0
							if(lines.length == 0) {
								poundage = 6;
							} else {
								poundage = 0
							}
							lines.push({
								accId: allSubjects[index].accId,
								beginDate: allSubjects[index].beginDate,
								endDate: allSubjects[index].endDate,
								payTotal: allSubjects[index].payTotal,
								payedTotal: allSubjects[index].payedTotal,
								subject: allSubjects[index].subject,
								unpayedTotal: allSubjects[index].unpayedTotal,
								bankCode: bankCode,
								poundage: poundage,
							})
						}
					}
				})
				if(isOk) {
					$('#needPay').html($(this).prev().html());
					$('.mask').show();
					tempPayPrice = Number($(this).prev().html());
					$("#wantPay").val(tempPayPrice);
				}
			}
		}
	})
	//关闭弹出框
	$('.closeConfirm').click(function() {
		$('.mask').hide();
	})

	/**
	 * 修改子账单的缴款数额，分配金额
	 * */
	function changePrice(value, line) {
		console.log(line)
		var tempCalcPayPrice = value; //获取更改后的值
		var templines = [].concat(line);
		var tempNum = true;
		for(var i = 0; i < templines.length; i++) {
			if(tempCalcPayPrice >= templines[i].unpayedTotal) {
				tempCalcPayPrice = (tempCalcPayPrice - templines[i].unpayedTotal).toFixed(2);
			} else {
				if(tempNum == true) {
					templines[i].unpayedTotal = Number(tempCalcPayPrice);
					tempNum = false;
					tempCalcPayPrice = 0;
				} else {
					templines[i].unpayedTotal = 0;
				}
			}
		}
		return templines;
	}

	/**
	 * 支付接口调用
	 * */
	function handlePay(tranType, tempLines) {
		var time = new Date().Format('yyyy-MM-dd hh:mm:ss');
		var operId = userInfo.code;
		var fullname = userInfo.name;
		var channel;
		for(var i = 0; i < userInfo.companies[contentType].channels.length; i++) {
			if(userInfo.companies[contentType].channels[i].type == "unionPay") {
				channel = userInfo.companies[contentType].channels[i];
			}
		}
		var postData = {
			channel: {
				contents: {
					appRequestUrl: channel.contents.appRequestUrl,
					rootCertPath: channel.contents.rootCertPath,
					signCertPath: channel.contents.signCertPath,
					signCertPwd: channel.contents.signCertPwd,
					signCertType: channel.contents.signCertType,
					frontUrl: channel.contents.frontUrl,
					backUrl: channel.contents.backUrl,
					merId: channel.contents.merchantId
				},
//				contents: {
//					appRequestUrl: "http://newpayment-test.chinapay.com/CTITS/service/rest/page/nref/000000000017/0/0/0/0/0",
//					rootCertPath: "D:\\data\\cert\\chinapay\\cp-test.cer",
//					signCertPath: "D:\\data\\cert\\chinapay\\111111.pfx",
//					signCertPwd: "010203",
//					signCertType: "PKCS12",
//					frontUrl: "http://dev.gomoretech.com/palmmall-web/payment/chinaPayFontCallback.thor",
//					backUrl: "http://dev.gomoretech.com/palmmall-server/payment/chinaPayCallback",
//					merId: "000001710231751"
//				},
				paymentType: channel.paymentType,
				type: channel.type,
			},
			lines: tempLines,
			method: "chinapay",
			paymentDate: time,
			tranType: tranType,
			commissionCharge: "6"
		};
		
		console.log(postData);
		
		function successFun(res) {
			billNumber = res.data.billNumber;
			sessionStorage.setItem('jf_billNumber', billNumber); //缓存到本地用于支付结果页查询账单状态

			var chinaPayment = res.data.chinaPayment;
			$('.payForm').attr('action', chinaPayment.PayUrl);
			$('.MerBgUrl').val(chinaPayment.MerBgUrl);
			$('.TranDate').val(chinaPayment.TranDate);
			$('.RemoteAddr').val(chinaPayment.RemoteAddr);
			$('.MerId').val(chinaPayment.MerId);
			$('.TranTime').val(chinaPayment.TranTime);
			$('.MerOrderNo').val(chinaPayment.MerOrderNo);
			$('.CurryNo').val(chinaPayment.CurryNo);
			$('.Version').val(chinaPayment.Version);
			$('.Signature').val(chinaPayment.Signature);
			$('.CommodityMsg').val(chinaPayment.CommodityMsg);
			$('.MerPageUrl').val(chinaPayment.MerPageUrl);
			$('.OrderAmt').val(chinaPayment.OrderAmt);
			$('.BusiType').val(chinaPayment.BusiType);
			$('.TranType').val(chinaPayment.TranType);

			console.log(res.data)
			$('.payForm').submit();
			$('.payedMask').show();
			var watch = setInterval(function() {
				function successFun(res) {
					var status = res.data.state;
					if(status == "FINISH") {
						window.location.reload();
					} else if(res.data.syncedErrorMsg){
						clearInterval(watch);
						$('.payedMask').hide();
						$('.confirmMask').show();
						$('.txtMain').html(res.data.syncedErrorMsg);
						$('#toPayBtn').click(function(){
							window.location.reload();
						})
					}
				}
				_http.queryStatus(billNumber, successFun);
			}, 1000)
		}
		_http.chinaPay(time, operId, fullname, postData, successFun);
	}

	/**
	 * 检验支付金额小数位数，支付
	 * */
	function checkPay(tranType, lines) {
		var wantPay = $('#wantPay').val();
		var needPay = Number($('#needPay').html());
		if(wantPay <= 0 || wantPay == '') {
			layer.msg("您的缴费金额必须大于0");
			return false;
		}else if(wantPay > needPay){
			layer.msg("总金额不能大于全部未缴金额");
			$('#wantPay').val(needPay);
			return false;
		}else if(wantPay.toString().split(".")[1] && wantPay.toString().split(".")[1].length > 2) {
			layer.msg("小数点后最多两位！");
			return false;
		} else {
			tempLines = changePrice(wantPay, lines)
			console.log(tempLines)
			handlePay(tranType, tempLines);
		}
	}

	/**
	 * 个人账户缴费
	 * */
	$('#personanlPay').click(function() {
		var tranType = "person";
		checkPay(tranType, lines);
	})
	/**
	 * 公司账户缴费
	 * */
	$('#companyPay').click(function() {
		var tranType = "company";
		checkPay(tranType, lines);
	})
})